<?php

namespace app\task\command\oilcard;

use app\admin\model\order\OilCard as OilCardOrder;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 充值失败订单自动退款[油卡].
 */
class AutoRefund extends Command
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        $this->setName('oilcard:autoRefund')
            ->setDescription('oilcard order auto refund');
    }

    /**
     * 执行指令.
     *
     * sudo -u www php /www/wwwroot/api/think oilcard:autoRefund
     *
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        echo '油卡充值失败订单自动退款--'.PHP_EOL;
        $lockKey = 'oilcard_order_auto_refund_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢'.PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

        $list = Db::name('oil_card_order')
            ->where('refund_status', 2)
            ->where('supplier_status', 4)
            ->limit(100)
            ->order('updated_at asc')
            ->select()
            ->toArray();

        $done = 0;
        $model = new OilCardOrder();
        foreach ($list as $order) {
            // todo 订单是否状态判断
            $res = $model->refund($order['id']);
            if (false === $res) {
                echo $order['id'].'--'.$model->getError().PHP_EOL;
            } else {
                ++$done;
            }
        }

        cache($lockKey, null);

        echo '油卡订单充值失败自动退款：成功退 '.$done.' 单'.PHP_EOL;
    }
}
